package com.sloth.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.JsonNode;
import com.sloth.service.AuthenticationService;
import com.sloth.util.HttpUtils;
import com.sloth.util.JsonUtil;
import okhttp3.*;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */

    @Override
    public String postForm(Map<String, String> params) throws IOException {
        String url = "https://eid.shumaidata.com/eid/check";
        String appCode = "0e990e3b647b425aa13bb44a9be6deeb";
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());

        String result = response.body().string();
        System.out.println("result: " + result);
        return result;
    }

    @Override
    public String img_base64(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("图片不能为空！");
        }
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (!".jpg".equals(fileType) && ".png".equals(fileType)) {
//            throw new BizException("图片格式仅支持JPG、PNG！");
            System.out.println("图片格式仅支持JPG、PNG！");
        }
        byte[] data = null;
        try {
            InputStream in = file.getInputStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    @Override
    public JsonNode getPersonCard(MultipartFile multipartFile) throws Exception {

        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "0e990e3b647b425aa13bb44a9be6deeb";
        String method = "POST";

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");

        Map<String, String> querys = new HashMap<String, String>();
        // 对图像进行base64编码
        String imgBase64 = img_base64(multipartFile);

        //configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", "face");

        String config_str = configObj.toString();

        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        if (configObj.size() > 0) {
            requestObj.put("configure", config_str);
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            String str;
            if (stat != 200) {
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
//                return ;
            }

            String res = EntityUtils.toString(response.getEntity());


            JSONObject res_obj = JSON.parseObject(res);


            String result = res_obj.toJSONString();
            int nameLeft = result.indexOf("\"name\":\"") + 8;
            int nameright = result.indexOf("\",\"angle\"");

            String perName = result.substring(nameLeft, nameright);


            int numLeft = result.indexOf("\"num\":\"") + 7;
            int numRight = result.indexOf("\",\"sex\"");

            String perNum = result.substring(numLeft, numRight);

//            System.out.println(res_obj.toJSONString());


            System.out.println(perName);
            System.out.println(perNum);


            Map<String, String> params = new HashMap<>();
            params.put("idcard", perNum);
            params.put("name", perName);
            System.out.println("personId: " + perNum);
            System.out.println("personName: " + perName);
            JsonNode person = JsonUtil.stringToJson(postForm(params));


            return person;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
